//dp[i][j]表示p串[0, j]的字符是否可以匹配s串[0, i]的字符
//如果p[j]是一个普通字符, dp[i][j] = (p[j] == s[i] && dp[i - 1][j - 1])
//如果p[j] == '.', dp[i][j] = dp[i - 1][j - 1]
//如果p[j] == '*'
    //如果p[j - 1] == '.', dp[i][j] = dp[i][j - 2] || dp[i - 1][j]
    //如果p[j - 1]为普通字符, dp[i][j] = dp[i][j - 2] || (p[j - 1] == s[i] && dp[i - 1][j])

//综上：
//如果p[j] != '*', dp[i][j] = (p[j] == s[i] || p[j] == '.') && dp[i - 1][j - 1]
//否则           , dp[i][j] = dp[i][j - 2] || ((p[j - 1] == '.' || p[j - 1] == s[i]) && dp[i - 1][j])
class Solution {
public:
    bool isMatch(string s, string p) {
        int m = s.size(), n = p.size();
        vector<vector<bool>> dp(m + 1, vector<bool>(n + 1, false));

        s = "|" + s;
        p = "|" + p;

        //初始化dp表
        //第一行，s为空串，如果p的偶数为为连续的'*'，形如: x*x*x*，那么*都可以将其和前面的字符变为空串，进行匹配因此为true
            //直到遇到一个偶数位不为'*'停止
        dp[0][0] = true;
        for (int i = 2; i < n + 1; i += 2)
        {
            if (p[i] == '*')
            {
                dp[0][i] = true;
                dp[0][i - 1] = true;
            }
            else
                break;
        }

        for (int i = 1; i < m + 1; i++)
        {
            for (int j = 1; j < n + 1; j++)
            {
                if (p[j] == '*')
                    dp[i][j] = dp[i][j - 2] || ((p[j - 1] == '.' || p[j - 1] == s[i]) && dp[i - 1][j]);
                else
                    dp[i][j] = (p[j] == s[i] || p[j] == '.') && dp[i - 1][j - 1];
            }
        }

        return dp[m][n];
    }
};